package com.cjm.one.security.service;


import com.cjm.one.common.constant.SecurityConstants;
import com.cjm.one.common.result.Result;
import com.cjm.one.model.system.entity.SysUserInfo;
import com.cjm.one.security.custom.CustomUser;
import com.cjm.one.system.client.SyStemUserClient;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;


@Slf4j
@Service
public class AdminUserDetailsService implements UserDetailsService {

    @Resource
    private SyStemUserClient syStemUserClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户登录，用户名为：{}", username);
        //根据用户的用户名获取用户信息
         Result<SysUserInfo> data = syStemUserClient.getUserByName(username, SecurityConstants.INNER);
         log.info("用户信息为data：{}", data);
         SysUserInfo sysUserInfo = data.getData();
//        SysUserInfo sysUserInfo = syStemUserClient.getUserByName(username).getData();

        log.info("用户信息为：{}", sysUserInfo);
        if(null == sysUserInfo) {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUserInfo.getUserStatus().equals('1')) {
            log.info("账号已禁用:{}",sysUserInfo.getUserStatus());
            throw new RuntimeException("账号已禁用");
        }
//        TODO：获取用户权限
        List<String> userPermsList = syStemUserClient.findUserPermsList(sysUserInfo.getId(),SecurityConstants.INNER).getData();
        log.info("用户权限为：{}",userPermsList);
        sysUserInfo.setUserPermsList(userPermsList);
        return new CustomUser(sysUserInfo);
    }
}